import { hasOwn, isPlainObject, uuid, isFunction, _typeof } from 'sf-utils2'

interface DataResponse {
  code?: number
  message?: string
  data?: any
}

const getData = (data: any): any => {
  if (isPlainObject(data) && hasOwn(data, 'code') && hasOwn(data, 'message')) {
    return data?.data || {}
  }
  return data
}

/**
 * 返回体封装
 * @param code
 * @param message
 * @param data
 * @return {{code: number, data: {}, message: string, responseId: string, responseTime: number}}
 * @constructor
 */
export class Result {
  constructor({ code = 200, message = 'ok', data = null }: DataResponse) {
    return {
      code,
      message,
      data: getData(data),
      responseId: uuid(),
      responseTime: Date.now()
    }
  }

  /**
   * 请求成功
   * @param data
   * @return {{code: number, data: {}, message: string, responseId: string, responseTime: number}}
   */
  static ok(data: any) {
    return new Result({ code: 200, data: getData(data) })
  }

  /**
   * 请求失败500
   * @param message
   * @return {{code: number, data: {}, message: string, responseId: string, responseTime: number}}
   */
  static err(message: string) {
    return new Result({ code: 500, data: null, message })
  }

  /**
   * 请求失败
   * @param code
   * @param message
   * @return {{code: number, data: {}, message: string, responseId: string, responseTime: number}}
   */
  static error(code: number = 500, message: string = '服务端内部错误😅') {
    return new Result({ code, data: null, message })
  }

  /**
   * 请求分页
   * @param opts
   * @return {{code: number, data: {}, message: string, responseId: string, responseTime: number}}
   */
  static page(opts: { dataList: any[]; mark: any } = { dataList: [], mark: {} }) {
    return new Result({ data: { dataList: opts.dataList, mark: Result.mark(opts.mark) } })
  }

  /**
   * 分页
   * @param mark
   * @return {{current: number, totalSummarize: any, size: number, totalPageCount: number, totalRowCount: number, subtotalSummarize: any, currentRowCount: number}}
   */
  static mark(mark: any = {}) {
    const page = {
      current: 1,
      size: 10,
      totalPageCount: 2,
      totalRowCount: 12,
      currentRowCount: 10,
      subtotalSummarize: null,
      totalSummarize: null
    }
    return { ...page, ...mark }
  }

  /**
   * 转化controllers 层
   * @param obj
   * @return {{}}
   */
  static transformControllers(obj: { [key: string]: any }) {
    return Object.entries(obj).reduce((pre: { [key: string]: any }, [k, v]: [string, any]) => {
      if (isFunction(v)) {
        pre[k] = async function (req: any, res: any) {
          try {
            await v.call(this, ...arguments)
          } catch (e) {
            console.log('错误信息:', e, '\n')
            res.send(Result.err(`错误信息：` + e.toString()))
          }
        }
      }
      return pre
    }, {})
  }
}

/**
 * 转化相应出来的data 数据
 */
export function transformResponseDataValue(response: any) {
  if (response && _typeof(response.data) != 'Blob') {
    // response.data = JSON.parse(
    //   JSON.stringify(response?.data).replace(/http:\/\/10\.86\.120\.250:19000/g, 'https://10.86.120.10:19000')
    // )
  }
}

export default { Result }
